
import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.auf.core.Controller;
import org.auf.core.ControllerFactory;
import org.auf.core.IView;
import org.auf.core.Privileges;
import org.auf.core.ScoreTimer;
import org.auf.model.jdbc.UserDAOJDBC;
import org.auf.to.User;

/**
 * Servlet implementation class for Servlet: FrontController
 *
 */
public class FrontController extends javax.servlet.http.HttpServlet implements
		javax.servlet.Servlet {
	static final long serialVersionUID = 1L;
	private static String ATTRIBUTE_ACTION = "action";
	static Logger log = Logger.getLogger(FrontController.class.getName());

	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public FrontController() {
		super();
	}

	@Override
	public void init() throws ServletException {
		super.init();
		ControllerFactory.getInstance().init(this);
		ScoreTimer.execute();
	}


	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		log.info("Peticion realizada");

	
		ControllerFactory controllerFactory = ControllerFactory.getInstance();

		String action = (String) request.getParameter(ATTRIBUTE_ACTION);
		
		Controller controller;
		
		if (action == null) {
			controller = controllerFactory.create("main");
		}
		else {
			controller = controllerFactory.create(action);
		}

		if (controller == null) {
			log.error("No se encontro el controlador '" + action + "'");
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		}

		controller.assignThread(request, response, this);

		if (controller.getPrivileges() == Privileges.PUBLIC) {
			controller.show();
			return;
		}

		HttpSession session = request.getSession(false);

		if (session == null) {
			log.info("No hay sesion, mostrando la pagina de login");
			controller = controllerFactory.create("showlogin");
			controller.assignThread(request, response, this);
			controller.show();
			return;
		}

		User user = UserDAOJDBC.getInstance().selectUserByid(
				(String) session.getAttribute("id"));

		if (user == null || (controller.getPrivileges() == Privileges.ADMIN)) {
			log.info("Esta tratando de acceder a un controlador para el cual no tiene privilegios.");
			response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
			return;
		}

		//Asignamos las variables globales al layout
		IView view = controller.getView();
		view.assignVar("user", user);
		controller.setUser(user);

		controller.show();

	}
}